package crud.verify;

import com.alibaba.fastjson.JSONObject;
import crud.domain.SysVerify;

import java.util.List;

public class ParamVerify {

    //输入参数校验 正则
    public static void doVerify(JSONObject reqBody, List<SysVerify> sysVerifyList) throws Exception {
        //校验
        for (SysVerify sysVerify : sysVerifyList) {
            String verifyParam = sysVerify.getVerifyParam();
            String verifyRegex = sysVerify.getVerifyRegex();
            String verifyDesc = sysVerify.getVerifyDesc();
            String paramValue = reqBody.getString(verifyParam);
            if (paramValue == null) {
                throw new Exception(String.format("参数校验未通过,参数为空[%s]", verifyParam));
            }
            boolean ret = paramValue.matches(verifyRegex);
            if (!ret) {
                throw new Exception(String.format("参数校验未通过,参数名[%s],参数值[%s],校验正则[%s],校验描述[%s]", verifyParam, paramValue, verifyRegex, verifyDesc));
            }
        }
    }

    //输入参数校验 添加操作
    public static void requiredFieldInsertCheck(JSONObject reqBody, String[] requiredFields) throws Exception {
        //校验
        for (String fieldName : requiredFields) {
            if (!reqBody.containsKey(fieldName) || reqBody.getString(fieldName) == null) {
                throw new Exception(String.format("参数校验未通过,参数不存在或为空[%s]", fieldName));
            }
        }
    }

    //输入参数校验 编辑操作
    public static void requiredFieldEditCheck(JSONObject reqBody, String[] requiredFields) throws Exception {
        //校验
        for (String fieldName : requiredFields) {
            if (reqBody.containsKey(fieldName) && reqBody.getString(fieldName) == null) {
                throw new Exception(String.format("参数校验未通过,参数为空[%s]", fieldName));
            }
        }
    }
}
